/*
 * create by Littleken at 2019/1/14 14:31
 */
package com.littleken.sellproject.utils;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;

/**
 * 完成json与类对象的转换
 */
@Slf4j
public class JsonMapper {

    //json object转换器
    private static ObjectMapper objectMapper = new ObjectMapper();

    //初始化
    static {
        // config，设置json转换规则
        //设置未知字段处理方式，排除为空的字段
        objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
    }

    /**
     * //把对象转换（序列化）成字符串
     * 使用方法：String json = JsonMapper.obj2String("对象")
     * @param src 需要转换的对象
     * @param <T>
     * @return json字符串
     */
    public static <T> String obj2String(T src) {
        if (src == null) {
            return null;
        }
        try {
            //若对象本身就是字符串，返回字符串，否则转换为string
            return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
        } catch (Exception e) {
            log.warn("parse object to String exception, error:{}", e);
            return null;
        }
    }

    /**
     * //把字符串转换（反序列化）成类对象
     * 使用方法：APPLE a = JsonMapper.string2Obj(APPLE, new TypeReference<APPLE>() {});
     * @param src json字符串
     * @param typeReference 需要转换的对象类型
     * @param <T>
     * @return 对象
     */
    public static <T> T string2Obj(String src, TypeReference<T> typeReference) {//需要转换成的object类型,<T>指定
        if (src == null || typeReference == null) {
            return null;
        }
        try {
            //若对象本身就是字符串，返回字符串，否则转换为对应object
            return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
        } catch (Exception e) {
            log.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", src, typeReference.getType(), e);
            return null;
        }
    }
    
}
